﻿using ChuanYe.CountyFireManagement.EF.MySQL.Models;
using ChuanYe.CountyFireManagement.Model;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ChuanYe.CountyFireManagement.BLL
{
    public class FireFightingForceBLL
    {
        #region 构造单例
        private FireFightingForceBLL() { }
        private static FireFightingForceBLL _instance;
        public static FireFightingForceBLL Instance
        {
            get
            {
                return _instance ?? (_instance = new FireFightingForceBLL());
            }
        }
        #endregion


        public ResultDto<List<FireMQTTResponseModel>> Add(List<Firefightingforce> infos)
        {
            ResultDto<List<FireMQTTResponseModel>> result = new ResultDto<List<FireMQTTResponseModel>>();

            if (infos.Count == 0)
            {
                result.Status = -3;
                result.Message = "Firefightingforce Add Data Is Null";
                return result;
            }
          
            var fireInfo = BLL.FireInfoBLL.Instance.Get(infos[0].FireId);
            if (fireInfo == null)
            {
                result.Status = -1;
                result.Message = "FireInfo Is Not Exist";
                return result;
            }
            var fireResponse = BLL.FireResponseBLL.Instance.Get(fireInfo.FireId).ToList();
            if (fireResponse == null || fireResponse.Count==0)
            {
                result.Status = -4;
                result.Message = "FireResponse Not Started";
                return result;
            }
            var responseLevel = fireResponse.Count == 0 ? 3 : fireResponse.FirstOrDefault().Level;
            using (CountyFireManagementContext ef = new CountyFireManagementContext())
            {
                //记录ID
                List<int> fightingForceIds = new List<int>();
                List<string> contents = new List<string>();

                if (infos != null && infos.Count > 0)
                {
                    List<FireMQTTResponseModel> messageModels = new List<FireMQTTResponseModel>();
                    var existUser = ef.Userinfo.Where(p => p.UserId == infos[0].UserId).FirstOrDefault();
                    foreach (var item in infos)
                    {
                        ef.Firefightingforce.Add(item);
                        ef.Entry<Firefightingforce>(item).State = EntityState.Added;
                        ef.SaveChanges();

                        var fireHeadquarterExist = ef.Fireheadquarter.Where(p => p.HeadquarterId == item.HeadquarterId).FirstOrDefault();
                        string content = string.Format(FireInfoTool.GetFireInfoRecordFormat((int)RecordType.扑救力量), fireHeadquarterExist.Name, item.TeamNum);
                        fightingForceIds.Add(item.FightingForceId);
                        contents.Add(content);
                        Message message = new Message();
                        message.FireId = fireInfo.FireId;
                        message.Type = (int)MessageType.调集扑救力量通知;
                        message.Content = string.Format(FireInfoTool.GetFireInfoMessageFormat(message.Type), fireInfo.FireName,existUser.RealName, responseLevel, item.TeamNum);
                        message.SendType = (int)MessageSendType.指定区域发送;
                        message.CustomData =item.HeadquarterId.ToString(); //特殊附带参数
                        message.IsRead = 0;
                        message.HandleTime = item.TransDatetime;
                        message.SendUserId = item.UserId;
                        message.Ip = fireInfo.Ip;
                        ef.Message.Add(message);
                        ef.Entry<Message>(message).State = EntityState.Added;
                        ef.SaveChanges();

                        #region 装载消息 指定区域发送
                        var headquarterInfo = ef.Fireheadquarter.Where(p => p.HeadquarterId == item.HeadquarterId).FirstOrDefault();
                        if (headquarterInfo != null)
                        {
                            var messageModel = MessageBLL.Instance.TransMessageToFireFightingForceMQTTResponseModel(message,
                                                      headquarterInfo.AddressCounty,
                                                      headquarterInfo.AddressTown, headquarterInfo.AddressVillage,
                                                      (int)RecordType.扑救力量);
                            messageModels.Add(messageModel);
                        }

                        #endregion
                    }
                   
                    if (existUser != null)
                    {
                        Record record = new Record();
                        record.FireId = fireInfo.FireId;
                        record.HandleTime = infos[0].TransDatetime;
                        record.Type = (int)RecordType.扑救力量;
                        record.UserId = infos[0].UserId;
                        record.Content = string.Join(@",", contents);
                        record.AddTime = infos[0].TransDatetime;
                        record.Ip = infos[0].Ip;
                        record.Applicant = fireInfo.Alarm;
                        record.CustomData = string.Join(",", fightingForceIds);
                        
                        ef.Record.Add(record);
                        ef.Entry<Record>(record).State = EntityState.Added;
                        ef.SaveChanges();
                    }
                    result.FirstParam = messageModels;
                }
            }
            return result;
        }

        public ResultDto<List<FireMQTTResponseModel>> Reply(Fireforcesupport info,List<SubFireForceSupportModel> subInfos)
        {
            ResultDto<List<FireMQTTResponseModel>> result = new ResultDto<List<FireMQTTResponseModel>>();
            if (subInfos.Count == 0)
            {
                result.Status = -3;
                result.Message = "Firefightingforce Team Data Is Null";
                return result;
            }
            var fireInfo = BLL.FireInfoBLL.Instance.Get(info.FireId);
            if (fireInfo == null)
            {
                result.Status = -1;
                result.Message = "FireInfo Is Not Exist";
                return result;
            }
            var userinfo = BLL.UserBLL.Instance.Get(info.UserId);
            if (userinfo == null)
            {
                result.Status = -4;
                result.Message = "UserId Is Not Exist";
                return result;
            }
            string areaName = string.Empty;
         
            using (CountyFireManagementContext ef = new CountyFireManagementContext())
            {
                if (!string.IsNullOrEmpty(userinfo.AddressCounty))
                {
                    var countyId = Convert.ToInt32(userinfo.AddressCounty);
                    var countyInfo = ef.Linchpin.Where(p => p.LinchpinId == countyId).FirstOrDefault();
                    if (countyInfo != null)
                    {
                        areaName +=countyInfo.LinchpinName;
                    }
                }
                if (!string.IsNullOrEmpty(userinfo.AddressTown))
                {
                    var townId = Convert.ToInt32(userinfo.AddressTown);
                    var townInfo = ef.Linchpin.Where(p => p.LinchpinId == townId).FirstOrDefault();
                    if (townInfo != null)
                    {
                        areaName +=string.IsNullOrEmpty(areaName)? townInfo.LinchpinName:","+ townInfo.LinchpinName;
                    }
                }
                if (!string.IsNullOrEmpty(userinfo.AddressVillage))
                {
                    var villageId = Convert.ToInt32(userinfo.AddressVillage);
                    var villageInfo = ef.Linchpin.Where(p => p.LinchpinId == villageId).FirstOrDefault();
                    if (villageInfo != null)
                    {
                        areaName += string.IsNullOrEmpty(areaName) ? villageInfo.LinchpinName : "," + villageInfo.LinchpinName;
                    }
                }
                int total = 0;
                string content = areaName + "对";
                content += string.Format("{0}已派出 {1} 支扑火队伍赶往现场，分别为：", fireInfo.FireName, subInfos.Count);
                for(int i = 0; i <subInfos.Count; i++)
                {
                    content += i + 1 + "：" + subInfos[i].CaptainName;
                    content += "(电话：" + subInfos[i].CaptainPhone + ")带领的";
                    content += subInfos[i].RankName + " ";
                    content += "人数： " + subInfos[i].Sum + " ";
                    total += subInfos[i].Sum;
                }
                content += " 共计：" + total + "人，";
                content += " 回复人：" + userinfo.RealName + " ";
                info.ForceSupportContent = content;
                ef.Fireforcesupport.Add(info);
                ef.Entry<Fireforcesupport>(info).State = EntityState.Added;
                ef.SaveChanges();
                

                Record record = new Record();
                record.FireId = fireInfo.FireId;
                record.HandleTime = info.TransDatetime;
                record.Type = (int)RecordType.调集回复;
                record.UserId = info.UserId;
                record.Content = content;
                record.AddTime = info.TransDatetime;
                record.Ip = info.Ip;
                record.Applicant = fireInfo.Alarm;
               
                ef.Record.Add(record);
                ef.Entry<Record>(record).State = EntityState.Added;

                Message message = new Message();
                message.FireId = fireInfo.FireId;
                message.Type = (int)MessageType.调集扑救力量回复;
                message.Content = string.Format(FireInfoTool.GetFireInfoMessageFormat(message.Type), fireInfo.FireName);
                message.SendType = (int)MessageSendType.下级向上级发送;
                message.IsRead = 0;
                message.HandleTime = info.TransDatetime;
                message.SendUserId = info.UserId;
                message.Ip = fireInfo.Ip;
                ef.Message.Add(message);
                ef.Entry<Message>(message).State = EntityState.Added;
                ef.SaveChanges();

                #region 装载消息
                List<Message> messages = new List<Message>() { message };
                result.FirstParam = MessageBLL.Instance.TransMessageToFireMQTTResponseModel(messages, record.Type.Value);
                #endregion
                return result;
            }

        }
    }
}
